<template>
  <div>
    <Breadcrumb :items="['menu.system', 'menu.system.userManagement']" />
    <div>
      <a-spin :loading="pageLoading?.loading" style="width: 100%">
        <CardConponents>
          <a-button type="primary" @click="handleClick">新增</a-button>
        </CardConponents>
        <!-- 列表 -->
        <CardConponents>
          <a-table :data="dataList?.list">
            <template #columns>
              <a-table-column title="id" data-index="id"></a-table-column>
              <a-table-column title="账号" data-index="username"></a-table-column>
              <a-table-column title="昵称" data-index="nickname"></a-table-column>
              <a-table-column title="手机号" data-index="tel"></a-table-column>
              <a-table-column title="状态" data-index="status">
                <template #cell="{ record }">
                  {{ showStatus(record) }}
                </template>
              </a-table-column>
              <a-table-column title="管理角色名称" data-index="SystemRole.Role.name"></a-table-column>
              <a-table-column title="创建时间" data-index="create_time">
                <template #cell="{ record }">
                  {{ record.create_time ? getTime(Number(record?.create_time)) : '' }}
                </template>
              </a-table-column>
              <a-table-column title="操作">
                <template #cell="{ record }">
                  <a-button type="primary" style="margin-right: 5px;" size="small"
                    @click="handleEdidClick(record)">编辑</a-button>
                  <a-button type="primary" size="small" @click="handleRoleEdidClick(record)">设置角色</a-button>
                  <a-popconfirm content="确定要删除吗?" type="error" @ok=handleDelClick(record)>
                    <a-button type="primary" status="danger" size="small">删除</a-button>
                  </a-popconfirm>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </CardConponents>
        <!-- 新增编辑弹窗 -->
        <a-modal :maskClosable=false v-model:visible="visible" title="新增" :footer="false">
          <a-form :model="form" @submit="handleSubmit">
            <a-form-item field="Username" label="用户名" :disabled="!showPassword"
              :rules="[{ required: true, message: '不能为空' }, { validator }]">
              <a-input v-model="form.Username" />
            </a-form-item>
            <a-form-item field="Password" label="密码" v-if="showPassword">
              <a-input v-model="form.Password" />
            </a-form-item>
            <a-form-item field="Tel" label="手机号" :rules="[{ required: true, message: '不能为空' }]">
              <a-input v-model="form.Tel" />
            </a-form-item>
            <a-form-item field="Headimg" label="头像">
              <UploadImg :headimg="form?.Headimg" :parentInfo="fileUpload" :changeForm="changeForm" :type="'img'" />
            </a-form-item>
            <a-form-item field="Nickname" label="Nickname" :rules="[{ required: true, message: '不能为空' }]">
              <a-input v-model="form.Nickname" />
            </a-form-item>
            <div class="btn">
              <a-button style="width: 100px;margin-right: 10px;" @click="cancelClick">
                取消
              </a-button>
              <a-button style="width: 100px;" type="primary" html-type="submit" long :loading="loading">
                提交
              </a-button>
            </div>
          </a-form>
        </a-modal>
        <!-- 选择角色弹窗 -->
        <a-modal v-model:visible="showRole" title="选择管理角色" :footer="false">
          <a-form :model="roleForm" @submit="handleRoleSubmit">
            <a-form-item field="Type" label="角色">
              <a-select :style="{ width: '320px' }" v-model="roleForm.RoleId" placeholder="请选择 ...">
                <a-option v-for="item in roleList.list " :value="item.id"
                  :disabled="item.id == form.Id ? true : false">{{
                    item.name }}</a-option>
              </a-select>
            </a-form-item>
            <div class="btn">
              <a-button style="width: 100px;" type="primary" html-type="submit" long :loading="loading">
                提交
              </a-button>
            </div>
          </a-form>
        </a-modal>
      </a-spin>
    </div>
  </div>
</template>


<script lang="ts" setup>
import CardConponents from '@/components/card/index.vue';
import { reactive, ref } from 'vue';
import useLoading from '@/hooks/loading';
import { add, edit, systemList, del } from '@/api/system';
import { listAll } from '@/api/role';
import { roleAdd, roleEdit } from '@/api/system_role';
import { Message } from '@arco-design/web-vue';
import { onMounted } from 'vue';
import UploadImg from '@/components/uploadImg/index.vue';
import { fileUpload } from '@/api/system'
import { getTime } from '@/utils/auth'

const { loading, setLoading } = useLoading();
const showPassword = ref(true)
const visible = ref(false);
const showRole = ref(false)
const dataList: any = reactive({
  list: [],
  total: 0
});
const roleList: any = reactive({
  list: []
})
const pageLoading: any = reactive({ loading: false });
const form: any = reactive({
  Username: '',
  Password: '',
  Tel: '',
  Headimg: '',
  Nickname: '',
});
const roleForm = reactive({
  SystemId: '',
  RoleId: '',
  Id: ''
})

onMounted(() => {
  getList()
});

const validator = (value: any, cb: any) => {
  return new Promise((resolve: any) => {
    const regex = /^[a-zA-Z0-9]*$/;
    if (!regex.test(value)) {
      cb('只能是数字和字母,不能有空格')
    }
    resolve()
  })
}

const clearForm = () => {
  form.Id = ''
  form.Username = ''
  form.Password = ''
  form.Tel = ''
  form.Headimg = ''
  form.Nickname = ''
}

const clearRoleForm = () => {
  roleForm.SystemId = ''
  roleForm.RoleId = ''
  roleForm.Id = ''

}

const getList = async () => {
  pageLoading.loading = true
  const res = await systemList({ data: { offset: 0, limit: 10 } })
  pageLoading.loading = false
  dataList.list = res?.data?.List
  dataList.total = res?.data?.Total
}

const showStatus = (value:any) => {
  return value.status === "1" || value.status === 1 ? '正常' : '禁止'
}

const cancelClick = () => {
  visible.value = false;
  clearForm()
};
const handleClick = () => {
  clearForm()
  showPassword.value = true
  visible.value = true;
};

const changeForm = (val: any) => {
  form.Headimg = val
}

// 新增和编辑提交
const handleSubmit = async ({ errors, values }: any) => {
  if (loading.value) return;
  if (!errors) {
    if (values.StatusEd == "true" || values.StatusEd == true) {
      values.Status = 1
    } else {
      values.Status = 0
    }
    try {
      setLoading(true);
      if (form.Id > 0) {
        const res: any = await edit(values);
        setLoading(false);
        if (res?.code == 1) {
          Message.success(res?.msg);
          visible.value = false;
          clearForm()
          getList()
        }
      } else {
        const res: any = await add(values);
        setLoading(false);
        if (res?.code == 1) {
          Message.success(res?.msg);
          visible.value = false;
          clearForm()
          getList()
        }
      }
    } catch (error) {
      setLoading(false);
    }
  }
};

// 编辑展开
const handleEdidClick = (value: any) => {
  visible.value = true;
  clearForm()
  form.Id = value.id
  showPassword.value = false
  form.Username = value.username
  form.Tel = value.tel
  form.Headimg = value.headimg
  form.Nickname = value.nickname
}

// 删除
const handleDelClick = async (value: any) => {
  const res: any = await del({ Id: value?.id });
  if (res?.code === 1) {
    Message.success('删除成功')
    getList()
  }
}

//角色设置弹框
const handleRoleEdidClick = async (value: any) => {
  showRole.value = true
  const res: any = await listAll({ data: {} });
  roleList.list = res.data
  roleForm.SystemId = value.id
  roleForm.Id = value.SystemRole.id
}

// 角色编辑提交
const handleRoleSubmit = async ({ errors, values }: any) => {
  if (values.Id > 0) {
    const res: any = await roleEdit(values);
    setLoading(false);
    if (res?.code == 1) {
      Message.success(res?.msg);
      showRole.value = false
      clearRoleForm()
      getList()
    }
  } else {
    const res: any = await roleAdd(values);
    setLoading(false);
    if (res?.code == 1) {
      Message.success(res?.msg);
      showRole.value = false
      clearRoleForm()
      getList()
    }
  }
}
</script>

<script lang="ts">
export default {
  name: 'UserManagement'
};
</script>

<style lang="less" scoped>
.btn {
  display: flex;
  justify-content: flex-end;
}
</style>
